package com.cuteboy.admin.service;

import com.cuteboy.dao.SysPermissionMapper;
import com.cuteboy.entity.SysPermission;
import com.cuteboy.util.ValidateUtils;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;

@Service
public class SysPermissionService {

    @Autowired
    @Qualifier("sysPermissionMapper")
    private SysPermissionMapper sysPermissionMapper;

    public JsonArray permissionTree(String parentCode){
        return getAllPermissionByParentCode(parentCode);
    }


    /**
     * 递归获取所有菜单
     * @param parentCode
     * @return
     */
    private JsonArray getAllPermissionByParentCode(String parentCode){
        // 第一步：获取父节点下的所有子节点
        JsonArray jsonArray = getPermissionJsonByParentCode(parentCode);
        // 第二步：遍历子节点，判断子节点是否 具有子节点，
        // 第三步：有-获取子节点的code，回到第一步
        // 第四步：没有子节点 | 遍历结束 > 将当前json数据做为子节点加入父节点


        for(int i=0;i<jsonArray.size();i++){
            JsonObject jsonObject = (JsonObject) jsonArray.get(i);
            //判断该节点下是否还有子节点
            Example example = new Example(SysPermission.class);
            example.or().andEqualTo("parentCode", jsonObject.get("code").getAsString());
            //if("true".equals(jsonObject.get("spread").getAsString())){
            if (sysPermissionMapper.selectCountByExample(example) == 0) {
                continue;
            }else{
                //二级或三级菜单
                jsonObject.add("children", getAllPermissionByParentCode(jsonObject.get("code").getAsString()));
            }
        }
        return jsonArray;
    }

    /**
     * 根据父节点，获取所有子节点的json数据
     * @param parentCode
     * @return
     */
    private JsonArray getPermissionJsonByParentCode(String parentCode) {
        Example example = new Example(SysPermission.class);
        example.or().andEqualTo("parentCode", parentCode);
        List<SysPermission> sysPermissionList = sysPermissionMapper.selectByExample(example);

        JsonArray jsonArray = new JsonArray();
        for(SysPermission sysPermission : sysPermissionList){
            JsonObject jsonObject=new JsonObject();
            jsonObject.addProperty("code", sysPermission.getCode()); // 节点id
            jsonObject.addProperty("flag", sysPermission.getFlag()); // 节点名称
            jsonObject.addProperty("name", sysPermission.getName()); // 不展开
            jsonObject.addProperty("orderBy", sysPermission.getOrderBy()); // 不展开
            jsonObject.addProperty("parentCode", sysPermission.getParentCode()); // 不展开
            jsonObject.addProperty("type", sysPermission.getType()); // 不展开
            jsonObject.addProperty("url", sysPermission.getUrl()); // 不展开
            jsonObject.addProperty("state", sysPermission.getState()); // 不展开
            jsonObject.addProperty("isOpen", sysPermission.getState() == 0 ? false : true); // 不展开
            jsonArray.add(jsonObject);
        }
        return jsonArray;
    }


    public SysPermission update(SysPermission entity) {
        if (!"1".equals(entity.getParentCode())){
            SysPermission parentPermission = getEntity(entity.getParentCode());
            if (ValidateUtils.isNull(parentPermission)){
                return null;
            }
        }
        sysPermissionMapper.updateByPrimaryKey(entity);
        return entity;
    }

    public SysPermission save(SysPermission entity) {
        sysPermissionMapper.insert(entity);
        return entity;
    }

    public SysPermission getEntity(String code) {
        return sysPermissionMapper.selectByPrimaryKey(code);
    }

    public String delete(String code){
        List<SysPermission> sysPermissionList = selectByParentCode(code);
        if (ValidateUtils.isNotEmpty(sysPermissionList)){
            return "当前权限具有下级权限，请先清空下级权限";
        }
        sysPermissionMapper.deleteByPrimaryKey(code);
        return "删除成功";
    }

    // ------------------------------------------------ 初始化后台管理导航菜单----------------------------------------

    /**
     * 获取根频道所有菜单信息
     * @param roleId
     * @return
     */
    public JsonArray getAllMenuByParentCode(String parentCode, Integer roleId){
        JsonArray resultArray = new JsonArray();
        JsonArray jsonArray = this.getMenuByParentCode(parentCode, roleId);//得到所有一级菜单
        for(int i = 0; i < jsonArray.size(); i++){
            JsonObject jsonObject = (JsonObject) jsonArray.get(i);
            //判断该节点下时候还有子节点
            Example example = new Example(SysPermission.class);
            example.or().andEqualTo("parentCode",jsonObject.get("code").getAsString());
            //if("true".equals(jsonObject.get("spread").getAsString())){
            if (selectCountByExample(example) == 0) {
                continue;
            }else{
                //由于后台模板的规定，一级菜单以title作为json的key
                jsonObject.add("children", getAllMenuJsonArrayByParentId(jsonObject.get("code").getAsString(),roleId));
            }
            resultArray.add(jsonObject);
        }
        return resultArray;
    }


    /**
     * 只获取二级权限菜单
     * @param parentCode
     * @param roleId
     * @return
     */
    private JsonArray getAllMenuJsonArrayByParentId(String parentCode,Integer roleId){
        JsonArray jsonArray = this.getMenuByParentCode(parentCode, roleId);
        return jsonArray;
    }

    /**
     * 根据父节点和用户角色id查询菜单
     * @param parentCode
     * @param roleId
     * @return
     */
    private JsonArray getMenuByParentCode(String parentCode,Integer roleId){
        //List<Menu> menuList=menuService.findByParentIdAndRoleId(parentId, roleId);
        HashMap<String,Object> paraMap = new HashMap<String,Object>();
        paraMap.put("parentCode",parentCode);
        paraMap.put("roleId",roleId);
        List<SysPermission> sysPermissionList = selectByParentIdAndRoleId(paraMap);
        JsonArray jsonArray = new JsonArray();
        for(SysPermission sysPermission : sysPermissionList){
            JsonObject jsonObject=new JsonObject();
            jsonObject.addProperty("code", sysPermission.getCode()); // 节点id
            jsonObject.addProperty("title", sysPermission.getName()); // 节点名称
            jsonObject.addProperty("spread", false); // 不展开
            if(ValidateUtils.isNotEmpty(sysPermission.getUrl())){
                jsonObject.addProperty("href", sysPermission.getUrl()); // 菜单请求地址
            }
            jsonArray.add(jsonObject);

        }
        return jsonArray;
    }

    public void putTmenuOneClassListIntoSession(HttpSession session){
        //用来在welcome.ftl中获取主菜单列表
        List<SysPermission> tmenuOneClassList = selectByParentCode("1");
        session.setAttribute("tmenuOneClassList", tmenuOneClassList);
    }

    /**
     * 根据父权限id获取子权限集合
     * @param parentCode
     * @return
     */
    public List<SysPermission> selectByParentCode(String parentCode){
        Example rolePermiExample = new Example(SysPermission.class);
        rolePermiExample.or().andEqualTo("parentCode", parentCode);
        return selectByExample(rolePermiExample);
    }

    public List<SysPermission> selectByParentIdAndRoleId(HashMap<String, Object> paraMap) {
        return sysPermissionMapper.selectByParentIdAndRoleId(paraMap);
    }

    public int selectCountByExample(Object o) {
        return sysPermissionMapper.selectCountByExample(o);
    }

    public List<SysPermission> selectByExample(Object o) {
        return sysPermissionMapper.selectByExample(o);
    }

}
